const express = require("express"); //引入服务
const session = require("express-session"); //引入session
const expressStatic = require("express-static"); //引入静态资源访问
const bodyParser = require("body-parser"); // 引入post提交的数据
const ejs = require("ejs"); //引入ejs
const mysql = require("mysql"); //引入mysql
const cookieParser = require("cookie-parser"); //引入cookie
const server = express(); //创建服务
// 使用bodyParser预处理post数据 (注意：bodyParser要配合use使用)
server.use(
  bodyParser.urlencoded({
    extended: false, // 不开启扩展模式
    limit: 1024 * 1024, // 限制post数据最大为1m
  })
);
server.use(bodyParser.json());
// 对所有请求设置响应头（设置允许跨域）
server.all("*", function (request, response, next) {
  response.header("Access-Control-Allow-Origin", "*");
  response.header("Access-Control-Allow-Methods", "*");
  response.header("Access-Control-Allow-Headers", "Content-Type");
  //response.header("Content-Type", "text/html;charset=utf-8");
  //response.header("Content-Type", "application/json;charset=utf-8");
  if (request.method.toLowerCase() == "options") {
    response.send(200); // 让options尝试请求快速结束 这样就可以解决客户端传json且跨域的问题
  } else {
    next();
  }
});
//创建数据库连接词
const pool = mysql.createPool({
  connectionLimit: 5, //最大连接数为5
  host: "localhost",
  port: 3306,
  database: "vue_findgoods",
  user: "root",
  password: "root",
});
//配置session
server.use(
  session({
    secret: "bobi susi", //设置session签名(可自定义)
    // 设置与session配套的cookie信息
    cookie: {
      maxAge: 1000 * 60, // 10秒钟后cookie过期
      secure: false, // 只有https协议才能访问cookie
    },
    resave: false, //强制保存session，即使它并没有更新
    saveUninitialized: true, // 强制保存未初始化的session 存储
    rolling: true, // 当客户端发送请求时，更新cookie有效期
  })
);
//配置cookie
server.use(cookieParser());

//用户登入
//登入
server.post("/api/login", function (request, response) {
  let reqObj = request.body;
  let sql = `select *,date_format(Regtimer, '%Y年-%m月-%d日 %H时:%i分') as date from gd_user where Username='${reqObj.username}' and Password='${reqObj.password}'`;
  pool.getConnection(function (err, connection) {
    //sql语句  回调函数
    connection.query(sql, function (err, rows) {
      if (err) {
        response.status(500).send("数据库出错").end();
      } else {
        if (rows.length == 0) {
          response.send({
            meta: {
              msg: "登入失败",
              status: 500,
            },
          });
        } else {
          request.session.user = reqObj.username;
          let meta = {
            msg: "登入成功",
            status: 200,
          };
          let successInfo = { data: { ...rows[0] }, meta: meta };
          response.send(successInfo);
        }
      }
    });
    connection.release(); //释放连接
  });
});

//#region 物品发布页
// 获取物品信息
server.get("/api/getGoods", (request, response) => {
  let sql = `select  *,date_format(Issuetimer, '%Y/%m/%d %H:%i') as fbtimer,date_format(Gettimer, '%Y/%m/%d %H:%i') as lqtimer from ug_v left join su_v on ug_v.id = su_v.ProductId`;
  //判断用户是否登入
  pool.getConnection(function (err, connection) {
    //sql语句  回调函数
    connection.query(sql, function (err, rows) {
      if (!err) {
        let meta = {
          msg: "获取物品信息成功",
          status: 200,
        };
        let successInfo = { data: rows, meta: meta };
        response.send(successInfo);
      } else {
        response.status(500).send("数据库出错").end();
      }
    });
    connection.release(); //释放连接
  });
});
// 物品信息搜索
server.get("/api/searchGoodsList", (request, response) => {
  let reqObj = request.query;
  let sql = `select  *,date_format(Issuetimer, '%Y/%m/%d %H:%i') as fbtimer,date_format(Gettimer, '%Y/%m/%d %H:%i') as lqtimer from ug_v left join su_v on ug_v.id = su_v.ProductId where Productname like '%${reqObj.keyWord}%';`;
  pool.getConnection(function (err, connection) {
    //sql语句  回调函数
    connection.query(sql, function (err, rows) {
      if (!err) {
        let meta = {
          msg: "物品信息搜索成功",
          status: 200,
        };
        let successInfo = { data: rows, meta: meta };
        response.send(successInfo);
      } else {
        response.status(500).send("数据库出错").end();
      }
    });
    connection.release(); //释放连接
  });
});
//#endregion

// 查看用户信息
server.get("/api/getUser", (request, response) => {
  let sql = `select *,date_format(Regtimer, '%Y/%m/%d %H:%i') as date from gd_user`;
  //判断用户是否登入
  pool.getConnection(function (err, connection) {
    //sql语句  回调函数
    connection.query(sql, function (err, rows) {
      if (!err) {
        let meta = {
          msg: "用户信息获取成功！",
          status: 200,
        };
        let successInfo = { data: rows, meta: meta };
        response.send(successInfo);
      } else {
        response.status(500).send("数据库出错").end();
      }
    });
    connection.release(); //释放连接
  });
});
// 搜索用户信息
server.get("/api/searchUser", (request, response) => {
  let reqObj = request.query;
  let sql = `select *,date_format(Regtimer, '%Y年-%m月-%d日 %H时:%i分') as date from gd_user where Username like '%${reqObj.keyWord}%';`;
  //判断用户是否登入
  pool.getConnection(function (err, connection) {
    //sql语句  回调函数
    connection.query(sql, function (err, rows) {
      if (!err) {
        let meta = {
          msg: "物品信息搜索成功",
          status: 200,
        };
        let successInfo = { data: rows, meta: meta };
        response.send(successInfo);
      } else {
        response.status(500).send("数据库出错").end();
      }
    });
    connection.release(); //释放连接
  });
});

//设置session接口
server.get("/setsession", function (request, response) {
  request.session.user = "张三";
  response.send("添加成功");
});
//读取session接口
server.get("/redsession", function (request, response) {
  console.log(request.session.user);
  response.send(request.session.user + "欢迎回来....");
});
server.use(express.static("./"));
server.listen(8008, function () {
  console.log("8008端口监听中……");
});
